package com.imdroid.lite.activities;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.R;
import com.imdroid.lite.model.TeamTalk;

/**
 * The activity of the team talk
 * 
 */
/**
 * @author hexuexun
 * 
 */
public class TeamTalkHistoryActivity extends BaseActivity {
	/**
	 * The tag of this class
	 */
	private final static String TAG = "TeamTalkHistoryActivity";
	/**
	 * The list view of the screen,
	 */
	private ListView listView;
	/**
	 * The datas
	 */
	private Collection<TeamTalk> teamTalks;
	/**
	 * The minimal width of the button
	 */
	private final static int minButtonWidth = 80;
	/**
	 * The maximal width of the button
	 */
	private int maxButtonWidth;
	
	private static TeamTalkHistoryActivity instance;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.lite.activities.BaseActivity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle bdl) {
		super.onCreate(bdl);
		setContentView(R.layout.team_talk_history);
		// 获取屏幕宽度，以他的75%为最大按钮长度
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		maxButtonWidth = (int) (metric.widthPixels * 0.75);

		// 初始化控件
		listView = (ListView) this.findViewById(R.id.team_talk_list);
		listView.setAdapter(new TeamTalkAdapter(this));
		instance = this;
	}
	
	public void onResume(){
		super.onResume();
		// 设置数据
		if (TeamMapActivity.instance != null)
			teamTalks = TeamMapActivity.instance.getTeamTalks();
		else
			teamTalks = new ArrayList<TeamTalk>();
		((TeamTalkAdapter) listView.getAdapter()).refresh();
	}

	/**
	 * Return to home activity
	 * 
	 * @param view
	 *            the button of return;
	 */
	public void back(View view) {
		this.finish();
	}

	/**
	 * The holder of the view
	 * 
	 */
	private final class ViewHolder {
		public TextView memberName;
		public Button speak;
		public int resId;
	}

	/**
	 * The adapter of the team talk
	 * 
	 */
	private class TeamTalkAdapter extends BaseAdapter {
		/**
		 * The context of the context
		 */
		private LayoutInflater layoutInflater;

		/**
		 * The context of the adapter
		 * 
		 * @param context
		 *            the context of the adapter
		 */
		public TeamTalkAdapter(Context context) {
			this.layoutInflater = LayoutInflater.from(context);
		}
		
		/**
		 * Refresh the view.
		 */
		public void refresh(){
			messageHandler.post(new Runnable(){
				public void run(){
					notifyDataSetChanged();
				}
			});
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		public int getCount() {
			if(teamTalks == null)
				return 0;
			return teamTalks.size();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItem(int)
		 */
		public Object getItem(int position) {
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return 0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = convertView == null ? null : (ViewHolder) convertView.getTag();
			// 获取对话
			Object[] items = teamTalks.toArray();
			final TeamTalk tt = (TeamTalk) items[position];
			boolean self = tt.getMemberId() == IMDroid.getUser().getUser_id();
			int leftRes = R.layout.team_talk_left;
			int rightRes = R.layout.team_talk_right;
			boolean needNew = convertView == null ? true : self ? leftRes != holder.resId : rightRes != holder.resId;
			if(needNew){
				holder = new ViewHolder();
				if(self){
					convertView = layoutInflater.inflate(leftRes, null);
					holder.memberName = (TextView) convertView
							.findViewById(R.id.team_talk_name_left);
					holder.speak = (Button) convertView
							.findViewById(R.id.team_talk_speak_left);
				} else {
					convertView = layoutInflater.inflate(rightRes, null);
					holder.memberName = (TextView) convertView
							.findViewById(R.id.team_talk_name_right);
					holder.speak = (Button) convertView
							.findViewById(R.id.team_talk_speak_right);
				}
				// 计算按钮的宽度，根据文件的大小，即说话的长短
				holder.speak.setWidth(getButtonWidth(tt.getFile()));
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			String time = null;
			if(position == 0){
				time = tt.getTime();
				tt.setTimeShowed(true);
			} else {
				int i = position;
				TeamTalk to = null;
				while(i >= 0){
					i --;
					to = (TeamTalk) items[i];
					if(!to.isTimeShowed())
						continue;
					break;
				}
				if(to != null && to.compareTime(tt) > 600000) { // 900000, fifteen minutes.
					time = tt.getTime();
					tt.setTimeShowed(true);
				} else {
					tt.setTimeShowed(false);
				}
			}
			holder.memberName.setText((time == null ? "" : time + " ") + tt.getMemberName());
			
//			if (convertView == null) {
//				holder = new ViewHolder();
//				// 如果对话是自己，则采用不同的layout
//				if (tt.getMemberId() == IMDroid.getUser().getUser_id()) {
//					convertView = layoutInflater.inflate(
//							R.layout.team_talk_left, null);
//					holder.memberName = (TextView) convertView
//							.findViewById(R.id.team_talk_name_left);
//					holder.speak = (Button) convertView
//							.findViewById(R.id.team_talk_speak_left);
//					holder.memberName.setText(tt.getMemberName() + ":");
//				} else {
//					convertView = layoutInflater.inflate(
//							R.layout.team_talk_right, null);
//					holder.memberName = (TextView) convertView
//							.findViewById(R.id.team_talk_name_right);
//					holder.speak = (Button) convertView
//							.findViewById(R.id.team_talk_speak_right);
//					holder.memberName.setText(":" + tt.getMemberName());
//
//				}
//				// 计算按钮的宽度，根据文件的大小，即说话的长短
//				holder.speak.setWidth(getButtonWidth(tt.getFile()));
//				convertView.setTag(holder);
//			} else {
//				holder = (ViewHolder) convertView.getTag();
//			}

			holder.speak.setText("" + tt.getLength() + "''");
			// 设置每个item的文本与按钮的事件 - 播放声音及改变按钮字体颜色
			final Button button = holder.speak;
			holder.speak.setOnClickListener(new View.OnClickListener() {
				/*
				 * (non-Javadoc)
				 * 
				 * @see
				 * android.view.View.OnClickListener#onClick(android.view.View)
				 */
				public void onClick(View v) {
					Log.d(TAG, tt.getFile());
					try {
						button.setTextColor(TeamTalkHistoryActivity.this
								.getResources().getColor(R.color.red));
						play(tt.getFile(), button);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			return convertView;
		}

		/**
		 * Get the button width according the length of the file
		 * 
		 * @param fileName
		 *            get the button width according the length of the file
		 * @return the width of the button
		 */
		private int getButtonWidth(String fileName) {
			File file = new File(fileName);
			if (!file.exists())
				return minButtonWidth;
			// 获取文件大小
			double fileSize = file.length();

			// 文件最大为100K, 按钮长度则按比例计算
			double maxSize = 30 * 1024;
			int width = (int) (fileSize / maxSize * (double) maxButtonWidth);
			if (width < minButtonWidth)
				return minButtonWidth;
			if (width > maxButtonWidth)
				return maxButtonWidth;
			return width;
		}

		/**
		 * @param fileName
		 *            the file of the sound.
		 * @param button
		 *            the button which clicking
		 * @throws Exception
		 */
		private void play(String fileName, final Button button)
				throws Exception {
			final MediaPlayer mediaPlayer = new MediaPlayer();
			final FileInputStream fis = new FileInputStream(fileName);
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setDataSource(fis.getFD());

			mediaPlayer
					.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
						public void onCompletion(MediaPlayer mp) {
							button.setTextColor(TeamTalkHistoryActivity.this
									.getResources().getColor(R.color.black));
							mediaPlayer.stop();
							mediaPlayer.release();
						}
					});
			mediaPlayer.prepare();
			mediaPlayer.start();
		}
	}
	
	public static class TalkCollection<T> extends ArrayList<T> {

		/**
		 *
		 */
		private static final long serialVersionUID = 2869021643072591788L;

		public boolean add(T t){
			boolean bool = super.add(t);
			if(instance != null){
				((TeamTalkAdapter)(instance.listView.getAdapter())).refresh();
			}
			if(TeamMapActivity.instance != null){
				if(t instanceof TeamTalk && ((TeamTalk) t).getFileNameInServer() != null)
					TeamMapActivity.instance.addNewTips();
			}
			return bool;
		}
		
	}

}
